package zconv

import (
	"bytes"
	"encoding/binary"
	"fmt"
)

const (
	DESC = "DESC" //倒序
	ASC  = "ASC"  //顺序
)

// NumberToStr 数值转字符串
func NumberToStr(number interface{}) (str string) {
	switch n := number.(type) {
	case uint8, uint16, uint32, uint64, uint, int8, int16, int32, int64, int:
		str = fmt.Sprintf("%d", n)
	case float32, float64:
		str = fmt.Sprintf("%f", n)
	}
	return
}

// ObjectToBytes 对象转byte数组,orderBy:数据流排序方式(ASC:正序,DESC:倒序)
func ObjectToBytes(obj interface{}, orderBy string) (buff []byte, e error) {
	bytesBuffer := bytes.NewBuffer([]byte{})
	if orderBy == ASC {
		e = binary.Write(bytesBuffer, binary.BigEndian, obj)

	} else if orderBy == DESC {
		e = binary.Write(bytesBuffer, binary.LittleEndian, obj)
	}

	buff = bytesBuffer.Bytes()
	return
}

// BytesToFloat byte数组转float,bitSize:数值的位数(取值32,64)
func BytesToFloat(buff []byte, bitSize int) (value interface{}, err error) {
	buf := bytes.NewBuffer(buff)
	switch bitSize {
	case 32:
		var f32 float32
		err = binary.Read(buf, binary.BigEndian, &f32)
		value = f32
	case 64:
		var f64 uint64
		err = binary.Read(buf, binary.BigEndian, &f64)
		value = f64
	}
	return
}

// BytesToObject byte转对像,orderBy:数据流是正序还是倒序(ASC:正序,DESC:倒序)
func BytesToObject(buff []byte, orderBy string, obj interface{}) (err error) {
	buf := bytes.NewBuffer(buff)
	var order binary.ByteOrder = binary.BigEndian
	if orderBy == DESC {
		order = binary.LittleEndian
	}
	err = binary.Read(buf, order, obj)
	return
}

// BytesToString []byte转成16进制字符串,separation=true时用逗号分隔
func BytesToString(buff []byte, separation bool) (str string) {
	if !separation {
		str = fmt.Sprintf("%x", buff)
		return
	}
	for i := 0; i < len(buff); i++ {
		str += fmt.Sprintf("%x,", buff[i])
	}
	str = str[:len(str)-1]
	return
}
